package com.copa.listener;

import com.copa.entity.Music;
import com.copa.entity.News;
import com.copa.provider.news.BaiduTopNews;
import com.copa.service.CommandService;
import com.copa.service.MusicFactory;
import com.copa.service.MusicService;
import com.copa.service.NewsService;
import com.copa.utils.MyCatCodeUtil;
import love.forte.simbot.annotation.*;
import love.forte.simbot.api.message.Reply;
import love.forte.simbot.api.message.ReplyAble;
import love.forte.simbot.api.message.events.GroupMemberIncrease;
import love.forte.simbot.api.message.events.GroupMsg;
import love.forte.simbot.api.sender.Sender;
import love.forte.simbot.filter.MatchType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.regex.Pattern;

import static com.copa.constant.Constants.GROUP_COMMAND;

/**
 * @author copa
 * @createDate 2022-02-23 12:02
 * @function 群聊
 */
@Component
public class GroupListener {

    @Autowired
    private CommandService commandService;

    @Autowired
    private NewsService newsService;

    @OnGroup
    @Filters(
            value = {
                    @Filter(value = "#热搜", matchType = MatchType.STARTS_WITH, trim = true, atBot = true),
                    @Filter(value = "#音乐", matchType = MatchType.STARTS_WITH, trim = true, atBot = true)
            }
    )
    public ReplyAble excludeCommand(GroupMsg msg) {
        String message = msg.getMsg().replace("[CAT:at,code=1150654809] ", "").trim();
        String pattern = "^(#热搜|#音乐)：.+";

        if (message.length() == 3
                || !Pattern.matches(pattern, message)) {
            return Reply.reply(commandService.findCommandByCommandAndType("error", GROUP_COMMAND), true);
        }
        return null;
    }
    /**
     * 指定新闻id发送
     * @param id
     * @return
     */
    @OnGroup
    @Filter(value = "#热搜：{{id}}", matchType = MatchType.REGEX_MATCHES, trim = true, atBot = true)
    public void getNewsReply(GroupMsg msg, Sender sender,
                             @FilterValue(value = "id") String id) {
        if (Integer.valueOf(id) <= 30) {
            News news = newsService.getNewsById(Integer.valueOf(id));
            sender.sendGroupMsg(msg.getGroupInfo().getGroupCode(),
                    MyCatCodeUtil.getAtPerson(msg.getAccountInfo().getAccountCode()) + "热榜新闻 " + id);
            sender.sendGroupMsg(msg.getGroupInfo().getGroupCode(),
                    MyCatCodeUtil.getShareNews(news));
            return;
        }
        sender.sendGroupMsg(msg.getGroupInfo().getGroupCode(),
                MyCatCodeUtil.getAtPerson(msg.getAccountInfo().getAccountCode())
                        + commandService.findCommandByCommandAndType("error", GROUP_COMMAND)
                        + commandService.findCommandByCommandAndType("#error热搜指令", GROUP_COMMAND));
    }

    /**
     * 骰子
     * @param msg
     * @param sender
     */
    @OnGroup
    @Filter(value = "#骰子", matchType = MatchType.STARTS_WITH, trim = true, atBot = true)
    public void groupDiceMessage(GroupMsg msg, Sender sender) {
        sender.sendGroupMsg(msg.getGroupInfo().getGroupCode(),
                MyCatCodeUtil.getAtPerson(msg.getAccountInfo().getAccountCode()) + "骰子");
        sender.sendGroupMsg(msg.getGroupInfo().getGroupCode(),
                MyCatCodeUtil.getDice());
    }

    @OnGroup
    @Filter(value = "#音乐：{{content}}", matchType = MatchType.REGEX_MATCHES, trim = true, atBot = true)
    public void groupMusicMessage(GroupMsg msg, Sender sender,
                                    @FilterValue(value = "content") String content) {

        if (!content.contains("#")) {
            sender.sendGroupMsg(msg.getGroupInfo().getGroupCode(),
                    MyCatCodeUtil.getAtPerson(msg.getAccountInfo().getAccountCode())
                            + commandService.findCommandByCommandAndType("error", GROUP_COMMAND)
                            + "\n" + commandService.findCommandByCommandAndType("#error音乐指令", GROUP_COMMAND));
            return;
        }
        String[] contentSplit = content.split("#");
        MusicService musicService = MusicFactory.getMusicService(contentSplit[0]);
        // 是否需要下载歌曲
        boolean needLink = contentSplit.length > 2 && "下载".equals(contentSplit[2]);
        Music music = musicService.searchMusicSync(contentSplit[1], needLink);
        sender.sendGroupMsg(msg.getGroupInfo().getGroupCode(),
                MyCatCodeUtil.getAtPerson(msg.getAccountInfo().getAccountCode())
                        + "音乐：" + contentSplit[1]);
        sender.sendGroupMsg(msg.getGroupInfo().getGroupCode(),
                MyCatCodeUtil.getMusicStr(music));
    }

    /**
     * 戳一戳机器人（双击头像，头像抖动）
     * @param
     * @return
     */
    @OnGroup
    public ReplyAble atNudgeAndErrorMessage(GroupMsg msg) {
        if (msg.getMsgContent().getCats().get(0).getType().contains("nudge")) {
            return Reply.reply(commandService.findCommandByCommandAndType("nudge", GROUP_COMMAND), true);
        }
        if (msg.getMsg().contains("[CAT:at,code=1150654809]")) {
            String message = msg.getMsg().replace("[CAT:at,code=1150654809]", "").trim();
            if (!message.contains("#")
                    || !commandService.findCountByCommandAndType(message, GROUP_COMMAND)) {
                return Reply.reply(commandService.findCommandByCommandAndType("error", GROUP_COMMAND), true);
            }
        }
        return null;
    }

    /**
     * 群成员入群欢迎
     * @param event
     * @param sender
     */
    @OnGroupMemberIncrease
    public void addGroupMember(GroupMemberIncrease event,
                               Sender sender) {
        if (!event.isBot()) {
            sender.sendGroupMsg(event.getGroupInfo().getGroupCode(),
                    MyCatCodeUtil.getAtPerson(event.getAccountInfo().getAccountCode())
                            + "欢迎 " + event.getAccountInfo().getAccountNickname() + " 进群喵~o(=•ェ•=)m\n"
                            + commandService.findCommandByCommandAndType("welcome", GROUP_COMMAND));
        }
    }

    /**
     * 帮助指令
     * @param
     * @return
     */
    @OnGroup
    @Filter(value = "#帮助", matchType = MatchType.STARTS_WITH, trim = true, atBot = true)
    public void atHelp(GroupMsg msg, Sender sender) {
        String msgContent = msg.getMsgContent().getMsg();
        if (msgContent.endsWith("#帮助")) {
            sender.sendGroupMsg(msg.getGroupInfo().getGroupCode(),
                    MyCatCodeUtil.getAtPerson(msg.getAccountInfo().getAccountCode()) +
                            commandService.findCommandByCommandAndType("#帮助", GROUP_COMMAND));
            return;
        }
        String[] split = msgContent.split("#");
        if (split.length > 2) {
            String remark = commandService
                    .findCommandByCommandAndType("#帮助#" + split[2], GROUP_COMMAND);
            if (Objects.nonNull(remark)) {
                sender.sendGroupMsg(msg.getGroupInfo().getGroupCode(),
                            MyCatCodeUtil.getAtPerson(msg.getAccountInfo().getAccountCode()) +
                                    remark);
                return;
            }
        }
        sender.sendGroupMsg(msg.getGroupInfo().getGroupCode(),
                MyCatCodeUtil.getAtPerson(msg.getAccountInfo().getAccountCode()) +
                        commandService.findCommandByCommandAndType("error", GROUP_COMMAND));
    }

}
